package com.cloudpivot.receivales.ding.scenegroup.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.ding.scenegroup.domain.*;
import com.cloudpivot.receivales.ding.scenegroup.service.CrmDingService;
import com.cloudpivot.receivales.ding.scenegroup.view.*;
import com.cloudpivot.receivales.ding.util.DingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class CrmDingServiceImpl implements CrmDingService {

    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;

    @Value("${myprops.crmurl}")
    private String CRMURL;

    @Value("${dingcallback.appkey}")
    private String APPKEY;
    @Value("${dingcallback.grouprobot}")
    private String GROUPROBOT;

    @Value("${dingcallback.orgrobot}")
    private String ORGROBOT;
    /**
     * 营销管理任务模版
     */
    @Value("${dingcallback.cardtemplateid}")
    private String CARDID;
    /**
     * 跳转链接的模版
     */
    @Value("${dingcallback.cardtempid2}")
    private String CARDID2;
    /**
     * 通用钉钉url互动模版
     */
    @Value("${dingcallback.cardtempid3}")
    private String CARDID3;


    /**
     * 获取 crm任务信息
     * @param guid
     */
    @Override
    public TaskManagerDTO getManagerTaskByGuid(String guid) {
        //获取 任务管理基本信息
        try {
            String url=String.format("%s%s",CRMURL,"/new_task_managements(" + guid + ")?$expand=owninguser($select=lastname),new_account_account($select=name),new_nodes($select=new_name),new_city($select=new_name),new_province($select=new_name)");
            log.info("打印需要请求crm的任务url--{}", url);
            //url编码
            url = DingUtil.urlEcode(url);
            String ret=httpAPIServiceForDing.doGetCrm(url);
            JSONObject retJson=JSONObject.parseObject(ret);
            TaskManagerDTO retTask = JSONObject.toJavaObject(retJson, TaskManagerDTO.class);
            //整理响应
            retTask.setNew_account_name(DingUtil.getJsonInsideValue(retJson.getJSONObject("new_account_account"),"name"));
            retTask.setOwnerid_name(DingUtil.getJsonInsideValue(retJson.getJSONObject("owninguser"),"lastname"));
            retTask.setNew_city_name(DingUtil.getJsonInsideValue(retJson.getJSONObject("new_city"),"new_name"));
            retTask.setNew_nodes_name(DingUtil.getJsonInsideValue(retJson.getJSONObject("new_nodes"),"new_name"));
            retTask.setNew_province_name(DingUtil.getJsonInsideValue(retJson.getJSONObject("new_province"),"new_name"));
            /**
             * kv 转换部分
             */
            //任务中类
            retTask.setNew_task_type2(TypeTwoEnum.getValue(retJson.getString("new_task_type2")));
            //任务大类
            retTask.setNew_task_type1(TypeOneEnum.getValue(retJson.getString("new_task_type1")));
            //目标转换
            retTask.setNew_final_type(FinalTypeEnum.getValue(retJson.getString("new_final_type")));
            //预计完成时间
            retTask.setNew_completion_quarter(CompletionQuarterEnum.getValue(retJson.getString("new_completion_quarter")));
            //状态
            retTask.setNew_task_state(TaskStateEnum.getValue(retJson.getString("new_task_state")));
            //任务等级
            retTask.setNew_level(LevelEnum.getValue(retJson.getString("new_level")));
            //计划内外
            retTask.setNew_yes_or_no(YesNoEnum.getValue(retJson.getString("new_yes_or_no")));
            //需要的支持
            retTask.setNew_support_nodes(SupportNodesEnum.getValue(retJson.getString("new_support_nodes")));
            //行数计算
            retTask.setSupport_rows(DingUtil.calRow(retJson.getString("new_support_work")).toString());
            retTask.setProgress_des_rows(DingUtil.calRow(retJson.getString("new_progress_description")).toString());
            retTask.setNext_rows(DingUtil.calRow(retJson.getString("new_next_plan")).toString());

            return retTask;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 卡片信息转换(crm 创建任务互动卡片用)
     * @param entity
     * @return
     */
    @Override
    public InteractiveCardDTO convertInteractiveCardDTO(TaskManagerDTO entity,String openConversationId) {
        String guid = DingUtil.getNewGUID();
        entity.setCheckflag("false");
        Map<String, String> cardParamMap = JSONObject.parseObject(JSONObject.toJSONString(entity), Map.class);
        log.info("转换的卡片信息（Map）为：{}", cardParamMap.toString());
        InteractiveCardDTO reEntity = new InteractiveCardDTO();
        InteractiveCardDTO.CardData carParam = new InteractiveCardDTO.CardData();
        carParam.setCardParamMap(cardParamMap);
        reEntity.setCardData(carParam);
        InteractiveCardDTO.CarOptions carOptions = new InteractiveCardDTO.CarOptions();
        carOptions.setSupportForward(true);
        reEntity.setCardTemplateId(CARDID); //固定模版
        reEntity.setOpenConversationId(openConversationId);
        reEntity.setOutTrackId(guid);
        reEntity.setConversationType(1);
        reEntity.setCallbackRouteKey(APPKEY); //中台场景群的appkey
        reEntity.setCardData(carParam);
        reEntity.setRobotCode(GROUPROBOT);
        reEntity.setUserIdType(1);
        reEntity.setAtOpenIds(new HashMap<String,String>().put("@ALL","@ALL")); //默认都是全员
        reEntity.setCardOptions(carOptions);
        log.info("转换成功的卡片信息（Map）为：{}", JSONObject.toJSONString(reEntity));
        return reEntity;
    }

    /**
     * 项目展示卡片（跳转类的卡片）
     * @param entity
     * @param openConversationId
     * @return
     */
    @Override
    public InteractiveCardDTO convertToProjectShowDTO(ProjectShowDTO entity, String openConversationId) {
        String guid = DingUtil.getNewGUID();
        Map<String, String> cardParamMap = JSONObject.parseObject(JSONObject.toJSONString(entity), Map.class);
        log.info("转换的项目卡片信息（Map）为：{}", cardParamMap.toString());
        InteractiveCardDTO reEntity = new InteractiveCardDTO();
        InteractiveCardDTO.CardData carParam = new InteractiveCardDTO.CardData();
        carParam.setCardParamMap(cardParamMap);
        reEntity.setCardData(carParam);
        InteractiveCardDTO.CarOptions carOptions = new InteractiveCardDTO.CarOptions();
        carOptions.setSupportForward(true);
        reEntity.setCardTemplateId(CARDID2); // 跳转模版
        reEntity.setOpenConversationId(openConversationId);
        reEntity.setOutTrackId(guid);
        reEntity.setConversationType(1);
        reEntity.setCallbackRouteKey(APPKEY); //中台场景群的appkey
        reEntity.setCardData(carParam);
        reEntity.setRobotCode(GROUPROBOT);
        reEntity.setUserIdType(1);
        reEntity.setAtOpenIds(new HashMap<String,String>().put("@ALL","@ALL")); //默认都是全员
        reEntity.setCardOptions(carOptions);
        log.info("转换成功的 项目 卡片信息（Map）为：{}", JSONObject.toJSONString(reEntity));
        return reEntity;
    }

    /**
     * 通用 url 钉钉互动卡片(没有场景群依托)
     * @param entity
     * @return
     */
    @Override
    public InteractiveCardDTO convertToUrlCardDTO(UrlCardDTO entity) {
        String guid = DingUtil.getNewGUID();
        String[] users=entity.getUserArray().split(",");
        if (StringUtils.isBlank(entity.getRowNum())) {
            entity.setRowNum("5");
        }
        Map<String, String> cardParamMap = JSONObject.parseObject(JSONObject.toJSONString(entity), Map.class);
        log.info("转换的项目卡片信息（Map）为：{}", cardParamMap.toString());
        InteractiveCardDTO reEntity = new InteractiveCardDTO();
        InteractiveCardDTO.CardData carParam = new InteractiveCardDTO.CardData();
        InteractiveCardDTO.CarOptions carOptions = new InteractiveCardDTO.CarOptions();
        carOptions.setSupportForward(false);
        reEntity.setCardOptions(carOptions);
        carParam.setCardParamMap(cardParamMap);
        reEntity.setCardData(carParam);
        reEntity.setCardTemplateId(CARDID3); // 跳转模版
        reEntity.setOutTrackId(guid);
        reEntity.setReceiverUserIdList(users);  //单聊对象（可以群发）
        reEntity.setConversationType(0);    //单聊
        reEntity.setRobotCode(ORGROBOT);
        reEntity.setUserIdType(1);
        log.info("转换成功的 项目 卡片信息（Map）为：{}", JSONObject.toJSONString(reEntity));

        return reEntity;
    }

    /**
     * 客户生日卡片 互动卡片模式
     * @param entity
     * @return
     */
    @Override
    public InteractiveCardDTO convertToBrithdayCardDTO(BirthdayCardDTO entity) {
        String guid = DingUtil.getNewGUID();
        String[] users=entity.getUserArray().split(",");
        if (StringUtils.isBlank(entity.getContent())) {
            //默认 无文本 5行
            entity.setContentRow("5");
        }else{
            int rowContentSize=entity.getContent().length();
            int rowSize=(rowContentSize / 16) < 5 ? 5:(rowContentSize / 16);
            entity.setContentRow(String.valueOf(rowSize));
        }
        Map<String, String> cardParamMap = JSONObject.parseObject(JSONObject.toJSONString(entity), Map.class);
        log.info("转换的项目卡片信息（Map）为：{}", cardParamMap.toString());
        InteractiveCardDTO reEntity = new InteractiveCardDTO();
        InteractiveCardDTO.CardData carParam = new InteractiveCardDTO.CardData();
        InteractiveCardDTO.CarOptions carOptions = new InteractiveCardDTO.CarOptions();
        carOptions.setSupportForward(false);
        reEntity.setCardOptions(carOptions);
        carParam.setCardParamMap(cardParamMap);
        reEntity.setCardData(carParam);
        reEntity.setCardTemplateId(entity.getCardType()); // 生日卡片(入参种类)
        reEntity.setOutTrackId(guid);
        reEntity.setReceiverUserIdList(users);  //单聊对象（可以群发）
        reEntity.setConversationType(0);    //单聊
        reEntity.setRobotCode(ORGROBOT);
        reEntity.setUserIdType(1);
        log.info("转换成功的 项目 卡片信息（Map）为：{}", JSONObject.toJSONString(reEntity));

        return reEntity;
    }
}
